# coding: utf-8
"""
@Time    : 2024/8/14 10:12
@Author  : Y.H LEE
"""

import datetime
import json
import pickle
import random
import matplotlib.pyplot as plt

import numpy as np
import torch
import torch.nn as nn
import os


def visual_training(step, size, loss):

    rate = (step + 1) / size
    a = "*" * int(rate * 50)
    b = "." * int((1 - rate) * 50)
    print("\rtrain loss: {:^3.0f}%[{}->{}] {:.3f} ".format(int(rate * 100), a, b, loss), end="")


def visual_per_epoch_loss(train_loss_list=None, valid_loss_list=None):

    if train_loss_list is None or not isinstance(train_loss_list, list):
        train_loss_list = []
    if valid_loss_list is None or not isinstance(valid_loss_list, list):
        valid_loss_list = []
    plt.figure()
    plt.plot(range(1, len(train_loss_list) + 1), train_loss_list, label='train_loss')
    plt.plot(range(1, len(valid_loss_list) + 1), valid_loss_list, label='valid_loss')
    plt.xticks(range(1, len(valid_loss_list) + 1))
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.title('loss_figure')
    plt.legend()
    plt.show()


def save_loss_list(loss_list, fp):
    with open(fp, 'w', encoding='utf-8') as fw:
        for loss in loss_list:
            fw.write(loss + '\n')


def lr_linear(optimizer, cur_epoch, init_lr, num_epoch_decay=10, dec_times=0.1, min_lr=1e-7):

    if init_lr <= min_lr:
        return init_lr
    lr = init_lr * (dec_times ** (cur_epoch // num_epoch_decay))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    return lr


class LRWarmUp:
    def __init__(self, optimizer, num_epochs, decay_fun='exp', max_lr=0.1, warm_up_steps=5, simu_exp_weight=1.0085):
        self.optimizer = optimizer
        self.lr_list = []
        for epoch in range(1, num_epochs + 1):
            if epoch <= warm_up_steps:
                warm_up_weight = epoch / float(warm_up_steps)
                self.lr_list.append(warm_up_weight * max_lr)
            else:
                if decay_fun == 'exp':
                    self.lr_list.append(self.lr_list[-1] ** simu_exp_weight)
                else:
                    self.lr_list.append(np.sin(self.lr_list[-1]))

    def get_lr(self, cur_epoch):
        for param_group in self.optimizer.param_groups:
            param_group['lr'] = self.lr_list[cur_epoch]
        return self.lr_list[cur_epoch]


def load_exists_model(abs_path, model, optimizer=None, load_epochs_state=True):

    if os.path.isfile(abs_path):
        checkpoint = torch.load(abs_path)
        model.load_state_dict(checkpoint['model'])
        if optimizer is not None:
            optimizer.load_state_dict(checkpoint['optimizer'])
        print('----------use exist model params-----------')
        print('model load successful!')
        if load_epochs_state:
            if checkpoint['epoch'] is None:
                return 0
            start_epoch = checkpoint['epoch'] + 1
            return start_epoch
        return 0
    else:
        print('no exist model params to load!')
        return 0


def set_seed(seed, device):

    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if device == 'cuda':
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)


def dict2json(dump_path, tgt_dict):

    with open(dump_path, 'w', encoding='utf-8') as f:
        json.dump(tgt_dict, f)


def obj2pickle(dump_path, tgt_obj):

    with open(dump_path, 'wb') as f:
        pickle.dump(tgt_obj, f)


def array2npy(dump_path, tgt_ndarray):

    np.save(dump_path, tgt_ndarray)


def load_json(fp):

    with open(fp, encoding='utf-8') as f:
        res_dict = json.load(f)
    return res_dict


def load_pickle(fp):

    with open(fp, 'rb') as f:
        res_pickle = pickle.load(f)
    return res_pickle


def get_cur_time():

    return datetime.datetime.now().strftime('%Y_%m_%d__%H_%M_%S')


def init_weights(model, non_linearity='relu'):
    for params in model.parameters():
        if params.dim() > 1:
            nn.init.kaiming_normal_(params, nonlinearity=non_linearity)
        else:
            # bias(params_dim=1)
            nn.init.constant_(params, 0)


def adjust_learning_rate(optimizer, epoch, args):
    # lr = args.learning_rate * (0.2 ** (epoch // 2))
    if args.lradj == 'type1':
        lr_adjust = {epoch: args.learning_rate * (0.5 ** ((epoch - 1) // 1))}
    elif args.lradj == 'type2':
        lr_adjust = {
            2: 5e-5, 4: 1e-5, 6: 5e-6, 8: 1e-6,
            10: 5e-7, 15: 1e-7, 20: 5e-8
        }
    if epoch in lr_adjust.keys():
        lr = lr_adjust[epoch]
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
        print('Updating learning rate to {}'.format(lr))


class EarlyStopping:
    def __init__(self, patience=7, verbose=False, delta=0):
        self.patience = patience
        self.verbose = verbose
        self.counter = 0
        self.best_score = None
        self.early_stop = False
        self.val_loss_min = np.Inf
        self.delta = delta

    def __call__(self, val_loss, model, path):
        score = -val_loss
        if self.best_score is None:
            self.best_score = score
            self.save_checkpoint(val_loss, model, path)
        elif score < self.best_score + self.delta:
            self.counter += 1
            print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            if self.counter >= self.patience:
                self.early_stop = True
        else:
            self.best_score = score
            self.save_checkpoint(val_loss, model, path)
            self.counter = 0

    def save_checkpoint(self, val_loss, model, path):
        if self.verbose:
            print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}).  Saving model ...')
        torch.save(model.state_dict(), path + '/' + 'checkpoint.pth')
        self.val_loss_min = val_loss


class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class StandardScaler():
    def __init__(self):
        self.mean = 0.
        self.std = 1.

    def fit(self, data):
        self.mean = data.mean(0)
        self.std = data.std(0)

    def transform(self, data):
        mean = torch.from_numpy(self.mean).type_as(data).to(data.device) if torch.is_tensor(data) else self.mean
        std = torch.from_numpy(self.std).type_as(data).to(data.device) if torch.is_tensor(data) else self.std
        return (data - mean) / std

    def inverse_transform(self, data):
        mean = torch.from_numpy(self.mean).type_as(data).to(data.device) if torch.is_tensor(data) else self.mean
        std = torch.from_numpy(self.std).type_as(data).to(data.device) if torch.is_tensor(data) else self.std
        if data.shape[-1] != mean.shape[-1]:
            mean = mean[-1:]
            std = std[-1:]
        return (data * std) + mean



if __name__ == '__main__':
    # train_loss_list = []
    # valid_loss_list = []
    # for i in range(20):
    #     train_loss_list.append(np.random.rand() * 20)
    #     valid_loss_list.append(np.random.rand() * 20)
    # visual_per_epoch_loss(train_loss_list, valid_loss_list)

    optimizer = list()
    lr_warm_up = LRWarmUp(optimizer, 20, max_lr=0.01, simu_exp_weight=1.055)
    lr_warm_up.get_lr(20)
